from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import unittest

class TestLoginPage(unittest.TestCase):
    """登录页面自动化测试"""
    def setUp(self):
        """每个测试用例执行前运行"""
        try:
            self.driver = webdriver.Edge()
            self.driver.implicitly_wait(10)
            self.driver.maximize_window()
            self.driver.get("http://127.0.0.1:8848/manage-project/login.html")
        except Exception as e:
            print(f"浏览器启动失败: {e}")
            raise

    def tearDown(self):
        """每个测试用例执行后运行"""
        try:
            self.driver.quit()
        except Exception as e:
            print(f"浏览器关闭失败: {e}")

    def test_successful_login(self):
        """测试成功登录"""
        try:
            print("开始测试：成功登录")
            username_input = self.driver.find_element(By.ID, "username")
            username_input.clear()
            username_input.send_keys("admin")
            print("已输入用户名")
            password_input = self.driver.find_element(By.ID, "password")
            password_input.clear()
            password_input.send_keys("admin123")
            print("已输入密码")
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not protocol_checkbox.is_selected():
                protocol_checkbox.click()
            print("已勾选协议")
            # 检查登录按钮是否可用
            login_button = self.driver.find_element(By.ID, "login-btn")
            if login_button.is_enabled():
                print("登录按钮可用，开始点击")
                login_button.click()
                time.sleep(2)
                try:
                    # 检查是否跳转到首页
                    if "app.html" in self.driver.current_url:
                        print("✅ 登录成功测试通过：成功跳转到首页")
                    else:
                        # 检查是否有成功提示
                        success_message = self.driver.find_element(By.CLASS_NAME, "toast")
                        if "成功" in success_message.text:
                            print("✅ 登录成功测试通过：显示成功提示")
                        else:
                            print("❌ 登录成功测试失败：未发现成功标识")
                    time.sleep(1)
                except:
                    print("❌ 登录成功测试失败：未跳转且无成功提示")
            else:
                print("❌ 登录按钮不可用")
        except Exception as e:
            print(f"❌ 成功登录测试执行失败: {e}")
            raise

    def test_login_without_protocol(self):
        """测试未勾选协议时登录"""
        try:
            print("开始测试：未勾选协议登录")
            time.sleep(2)
            username_input = self.driver.find_element(By.ID, "username")
            username_input.clear()
            username_input.send_keys("admin")
            password_input = self.driver.find_element(By.ID, "password")
            password_input.clear()
            password_input.send_keys("admin123")
            # 不勾选协议
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if protocol_checkbox.is_selected():
                protocol_checkbox.click()
            login_button = self.driver.find_element(By.ID, "login-btn")
            if not login_button.is_enabled():
                print("✅ 未勾选协议测试通过：登录按钮被禁用")
            else:
                print("❌ 未勾选协议测试失败：登录按钮仍然可用")
            time.sleep(2)
        except Exception as e:
            print(f"❌ 未勾选协议测试执行失败: {e}")
            raise

    def test_login_with_wrong_password(self):
        """测试错误密码登录"""
        try:
            print("开始测试：错误密码登录")
            time.sleep(2)
            # 输入正确的用户名和错误的密码
            username_input = self.driver.find_element(By.ID, "username")
            username_input.clear()
            username_input.send_keys("admin")
            password_input = self.driver.find_element(By.ID, "password")
            password_input.clear()
            password_input.send_keys("wrongpassword23")
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not protocol_checkbox.is_selected():
                protocol_checkbox.click()
            login_button = self.driver.find_element(By.ID, "login-btn")
            if login_button.is_enabled():
                login_button.click()
                time.sleep(3)
                # 检查是否有错误提示
                try:
                    error_message = self.driver.find_element(By.CLASS_NAME, "toast")
                    if "错误" in error_message.text or "失败" in error_message.text:
                        print("✅ 错误密码测试通过：显示错误提示")
                    else:
                        print("❌ 错误密码测试失败：错误提示内容不正确")
                except:
                    print("❌ 错误密码测试失败：未显示错误提示")
            else:
                print("❌ 登录按钮不可用")
        except Exception as e:
            print(f"❌ 错误密码测试执行失败: {e}")
            raise

    def test_login_with_wrong_username(self):
        """测试错误账号名登录"""
        try:
            print("开始测试：错误账号登录")
            time.sleep(2)
            # 输入正确的用户名和错误的密码
            username_input = self.driver.find_element(By.ID, "username")
            username_input.clear()
            username_input.send_keys("Admin123")
            password_input = self.driver.find_element(By.ID, "password")
            password_input.clear()
            password_input.send_keys("admin123")
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not protocol_checkbox.is_selected():
                protocol_checkbox.click()
            login_button = self.driver.find_element(By.ID, "login-btn")
            if login_button.is_enabled():
                login_button.click()
                time.sleep(3)
                try:
                    error_message = self.driver.find_element(By.CLASS_NAME, "toast")
                    if "错误" in error_message.text or "失败" in error_message.text:
                        print("✅ 错误用户名测试通过：显示错误提示")
                    else:
                        print("❌ 错误用户名测试失败：错误提示内容不正确")
                except:
                    print("❌ 错误用户名测试失败：未显示错误提示")
            else:
                print("❌ 登录按钮不可用")
        except Exception as e:
            print(f"❌ 错误用户名测试执行失败: {e}")
            raise

    def test_empty_username(self):
        """测试用户名为空"""
        try:
            print("开始测试：用户名为空")
            time.sleep(2)
            # 只输入密码
            password_input = self.driver.find_element(By.ID, "password")
            password_input.clear()
            password_input.send_keys("admin123")
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not protocol_checkbox.is_selected():
                protocol_checkbox.click()
            login_button = self.driver.find_element(By.ID, "login-btn")
            if not login_button.is_enabled():
                print("✅ 用户名为空测试通过：登录按钮被禁用")
            else:
                print("❌ 用户名为空测试失败：登录按钮仍然可用")
            time.sleep(2)
        except Exception as e:
            print(f"❌ 用户名为空测试执行失败: {e}")
            raise

    def test_empty_password(self):
        """测试密码为空"""
        try:
            print("开始测试：密码为空")
            time.sleep(2)
            # 只输入用户名
            username_input = self.driver.find_element(By.ID, "username")
            username_input.clear()
            username_input.send_keys("admin")
            protocol_checkbox = self.driver.find_element(By.CSS_SELECTOR, '#login-form > div.checkbox-group > label > span')
            if not protocol_checkbox.is_selected():
                protocol_checkbox.click()
            login_button = self.driver.find_element(By.ID, "login-btn")
            if not login_button.is_enabled():
                print("✅ 密码为空测试通过：登录按钮被禁用")
            else:
                print("❌ 密码为空测试失败：登录按钮仍然可用")
            time.sleep(2)
        except Exception as e:
            print(f"❌ 密码为空测试执行失败: {e}")
            raise

# 运行测试
if __name__ == "__main__":
    # 创建测试套件
    test_suite = unittest.TestSuite()
    # 添加测试用例（可以单独运行某个测试）
    test_suite.addTest(TestLoginPage('test_successful_login'))
    test_suite.addTest(TestLoginPage('test_login_without_protocol'))
    test_suite.addTest(TestLoginPage('test_login_with_wrong_password'))
    test_suite.addTest(TestLoginPage('test_login_with_wrong_username'))
    test_suite.addTest(TestLoginPage('test_empty_username'))
    test_suite.addTest(TestLoginPage('test_empty_password'))
    # 运行测试
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(test_suite)
    # 输出测试结果
    print("\n" + "=" * 50)
    print("测试报告:")
    print(f"总测试用例: {result.testsRun}")
    print(f"失败: {len(result.failures)}")
    print(f"错误: {len(result.errors)}")
    print("=" * 50)